var that;
var dtask;
import {md5} from '@/utils/MD5.js';

export default{
	data(){
		return{
			/* 更新数据 */
			isUpdate:false,
			forceUpdate:false,//强制更新
			upDateData:"",
			progress:0,
			totalSize:0,
			downloadedSize:0,
			showUpLoad:false,
			silent:false
		}
	},
	onLoad(){
		that=this;
	},
	methods: {
		upDateCheck(){
			plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {  
				that.$https.POST({
					url: '/public/version',  //请求更新接口
					data: {  
						versionNumber: widgetInfo.version,  //版本号
					},  
					success: (res) => {  
						// console.log(res)
						var data=res.data;
						that.isUpdate=data.isUpdate;
						that.forceUpdate=data.forceUpdate;
						// that.isUpdate=true;
						// that.forceUpdate=false;
						// data.doenloadLink="https://github.com/annywu/scroll_test/blob/gh-pages/myh1.0.3.apk?raw=true"
						// data.doenloadLink="https://github.com/annywu/scroll_test/blob/gh-pages/myh1.0.5.wgt?raw=true";
						// data.type=1;
						// data.silent=true;
						if(data.silent&&data.type==0){//静默安装=>下载安装包，下次启动app时更新
							that.isUpdate=false;
							let isinstall = that.$store.state.isInstall;
							if(!isinstall){
								downloadwgt()
							}
							function downloadwgt(){
								let downurl_md5           = md5(data.doenloadLink);  
								let local_down_url = "_downloads/update/"+downurl_md5+".wgt";
								dtask = plus.downloader.createDownload( data.doenloadLink,{filename:local_down_url},(d,status)=>{
									if(status!=200){
										console.log('下载失败')
										that.clearDownload(local_down_url)
									}
								}); 
								dtask.addEventListener("statechanged", onStateChanged, false);
								dtask.start();
								function onStateChanged(download, status) {
									var current;
									if(download.state==0){//下载任务开始调度
										if(!that.hasNetwork){
											that.clearDownload(local_down_url)
										}
									}
									// if(download.state==3){
									// 	current = parseInt(100 * download.downloadedSize / download.totalSize);
									// 	console.log(current)
									// }
									if(download.state == 4 && status == 200){
										console.log('下载成功'+download.filename)
										plus.runtime.install(download.filename,{}, function() {  
											console.log("安装成功")
											that.$store.commit('changeInstall')
											that.clearDownload()
										},function(e){  
											console.log("安装失败")
											that.clearDownload(local_down_url)
										})  
									}
								}
							}
						}
						that.upDateData=data;
					}
				})
			})
		},
		bepDate(){//立即更新
			if(that.showUpLoad){
				return;
			}
			let upDateData=this.upDateData;
			let updateType=upDateData.type;
			// 热更新
			if(updateType==0){
				if (upDateData.doenloadLink) { 
					if(upDateData.silent){//静默安装=>下载安装包，下次启动app时更新
						
					}else{//非静默安装
					that.showUpLoad=true;
					dtask = plus.downloader.createDownload( upDateData.doenloadLink,{},(d,status)=>{
						console.log('status:'+status)
						if(status!=200){
							plus.nativeUI.alert("下载失败"); 
							that.clearDownload()
							that.showUpLoad=false;
							that.isUpdate=false;
						}
					});  
					dtask.addEventListener("statechanged", onStateChanged, false);
					dtask.start();
					function onStateChanged(download, status) {
						var current;
						if(download.state==0){//下载任务开始调度
							if(!that.hasNetwork){
								that.showUpLoad=false;
								that.progress=0;
								that.totalSize=0;
								that.downloadedSize=0;
								that.clearDownload()
								plus.nativeUI.alert("网络已断开链接,请检查网络状态"); 
								// dtask.pause()
							}
						}
						if(download.state==3){//下载任务接收数据
							that.totalSize=(download.totalSize/1024/1024).toFixed(2);
							that.downloadedSize=(download.downloadedSize/1024/1024).toFixed(2);
							current = parseInt(100 * download.downloadedSize / download.totalSize);
							that.progress=current;
						}
						if(download.state == 4 && status == 200){// 下载完成 
							plus.runtime.install(download.filename, {  //安装
								force: true  
							}, function() {  
								that.showUpLoad=false;
								plus.nativeUI.alert("应用资源更新完成，重新启动程序！",function(){  
									that.isUpdate=false;
									plus.runtime.restart();  //重启
								});  
							}, function(e) { 
								that.showUpLoad=false;
								that.isUpdate=false;
								that.clearDownload()
								plus.nativeUI.alert("安装wgt文件失败["+e.code+"]："+e.message); 
							});  
						} 
					}
					}
				}
			}
			const isIOS=()=>{
				if(uni.getSystemInfoSync().platform === 'android'){
					return false
				}else{
					return true
				}
			}
			if(updateType==1){//整包更新
				let isios=isIOS();
				let downloadUrl="";
				downloadUrl=upDateData.doenloadLink;
				// plus.runtime.openURL(downloadUrl);  
				if(isios){//ios平台
					plus.runtime.openURL(downloadUrl);  
				}else{//andriod平台
					that.showUpLoad=true;
					dtask = plus.downloader.createDownload( downloadUrl,{},(download,status)=>{
						console.log('status:'+status)
						if(status!=200){
							plus.nativeUI.alert("下载失败"); 
							that.showUpLoad=false;
							that.isUpdate=false;
						}
					});  
					dtask.addEventListener("statechanged", onStateChanged, false);
					dtask.start();
					function onStateChanged(download, status) {
						var current;
						if(download.state==0){//下载任务开始调度
							if(!that.hasNetwork){
								that.showUpLoad=false;
								that.progress=0;
								that.totalSize=0;
								that.downloadedSize=0;
								that.clearDownload()
								plus.nativeUI.alert("网络已断开链接,请检查网络状态"); 
								// dtask.pause()
							}
						}
						if(download.state==3){//下载任务接收数据
							that.totalSize=(download.totalSize/1024/1024).toFixed(2);
							that.downloadedSize=(download.downloadedSize/1024/1024).toFixed(2);
							current = parseInt(100 * download.downloadedSize / download.totalSize);
							that.progress=current;
						}
						if(download.state == 4 && status == 200){// 下载完成 
							plus.nativeUI.alert("下载完成！");  
							plus.runtime.install(plus.io.convertLocalFileSystemURL(download.filename),{}, function() {  
								that.showUpLoad=false;
								plus.nativeUI.alert("应用资源安装成功！");  
							},function(e){  
								that.showUpLoad=false;
								that.clearDownload()
								plus.nativeUI.alert("安装失败["+e.code+"]："+e.message); 
							})  
						} 
					}
				}
			}
		},
		clearDownload(local_down_url){
			dtask.abort()
			dtask=null;
			plus.downloader.clear();
			if(local_down_url){
				plus.io.resolveLocalFileSystemURL(local_down_url, function(entry) {  
					entry.remove(function(entry) {  
						console.log("临时文件删除成功" + local_down_url);  
					}, function(e) {  
						 console.log("临时文件删除失败" + local_down_url);  
					});  
				});  
				local_down_url=""
			}
		},
		close2(){
			if(this.forceUpdate)return;
			this.isUpdate=false;
			if(dtask){
				dtask.abort()
				dtask=null;
				plus.downloader.clear();
			}
		},
	},
	watch:{
		isUpdate(newValue,oldValue){
			if(newValue){
				uni.hideTabBar()
			}else{
				uni.showTabBar()
			}
		},
		hasNetwork(newValue,oldValue){//网络状态
			if(newValue){
				if(this.isUpdate){
					this.bepDate()
					// dtask.resume()
					// dtask.start()
				}
			}
		}
	}
	
}